package org.codefinger.dao.impl.sql;

import org.codefinger.dao.impl.SQLVisitor;

public class Order {

	private OrderItem[]	orderItems;

	public Order(OrderItem[] orderItems) {
		super();
		this.orderItems = orderItems;
	}

	public void visit(SQLVisitor visitor) {
		visitor.appendSQL(" ORDER BY ");
		int[] orders = visitor.getOrders();
		OrderItem[] orderItems = this.orderItems;
		boolean flag = false;
		if (orders == null) {
			for (OrderItem item : orderItems) {
				if (flag) {
					visitor.appendSQL(',');
					item.visit(visitor);
					continue;
				}
				item.visit(visitor);
				flag = true;
			}
			return;
		}
		int forCount = Math.min(orders.length, orderItems.length);
		int orderIndex;
		int maxIndex = orderItems.length - 1;
		for (int i = 0; i < forCount; i++) {
			orderIndex = orders[i];
			if (orderIndex > maxIndex) {
				continue;
			}
			if (flag) {
				visitor.appendSQL(',');
				orderItems[orderIndex].visit(visitor);
				continue;
			}
			orderIndex = orders[i];
			orderItems[orderIndex].visit(visitor);
			flag = true;
		}
		if (!flag) {
			visitor.back(visitor.getSqlSize() - 10);
		}
	}
}
